/*
 * Copyright 2009 Gary Brown
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *
 * Change History:
 * 18 Mar 2009 : Initial version created by gary
 */
package org.betonthemove.ui.android;

import org.betonthemove.platform.*;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.*;

public class BetView extends Activity implements Runnable {

    private static final int CANCEL_BET_STATE = 50;
	private static final int ERROR_STATE = 100;
	private static final int ERROR_MESSAGE_DISPLAY_DELAY = 4000;
	private static final int WAITING_DIALOG = 1;
    private static final int ERROR_DIALOG = 2;
    private static final int CANCEL_BET_DIALOG = 3;
	private static final int VIEW_MARKET_ID = 1;
	private static final int CANCEL_UNMATCHED_BET_ID = 2;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.betview);

        runOnUiThread(this);   
    }
		
	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case WAITING_DIALOG: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setMessage("Retrieving bets...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
            case ERROR_DIALOG: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setMessage("ERROR: "+m_error);
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
            case CANCEL_BET_DIALOG: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setMessage("Cancelling bet...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
        }
        return null;
    }

    public void run() {
    	    	
    	if (m_state == 0) {
    		showDialog(WAITING_DIALOG);
    		
    		m_state++;
    		
    		new Thread(this).start();
    	} else if (m_state == 1) {

    		BettingPlatform platform=BettingPlatformFactory.getBettingPlatform();
        
	        try {
		        m_bets = platform.getBets();
		        
	    		m_currency = DisplayHelper.getCurrencySymbol(
    					platform.getCurrency());
		        
		        m_state++;
	        } catch(Exception e) {
	        	m_error = e.getLocalizedMessage();
	        	
	        	m_state = ERROR_STATE;
	        }
	        
	        runOnUiThread(this);

    	} else if (m_state == 2) {
    		
    		TableLayout tl=(TableLayout)findViewById(R.id.betview); 
    		
    		for (int i=0; i < m_bets.size(); i++) {
    			Bet bet=m_bets.get(i);
    			
    			TableRow row=new TableRow(this);
    			row.setPadding(1, 1, 1, 1);
    			row.setTag(bet);
   			
    			TextView text=new TextView(this);
    			text.setText(bet.getEntrantName()+"\n"+bet.getMarketName());
    			
    			if (bet.isMatched()) {
    				text.setTextColor(0xff111111);
    			} else {
    				text.setTextColor(R.color.black);
    			}
    			text.setWidth(160);
    			
    			row.addView(text);
    			
    			TextView odds=new TextView(this);
    			odds.setText(""+bet.getOdds()+"\n");
    			odds.setWidth(80);
    			odds.setPadding(2, 0, 0, 0);
    			odds.setTextColor(0xff111111);
    			
    			if (bet.isBack()) {
    				odds.setBackgroundDrawable(getResources().getDrawable(R.drawable.back));
    			} else {
    				odds.setBackgroundDrawable(getResources().getDrawable(R.drawable.lay));
    			}
   			
    			//odds.setOnClickListener(this);
    			
    			row.addView(odds);
    			
    			TextView price=new TextView(this);
    			price.setText(m_currency+bet.getStake()+"\n");
    			price.setWidth(80);
    			price.setPadding(2, 0, 0, 0);
    			price.setTextColor(0xff111111);
    				
    			if (bet.isBack()) {
    				price.setBackgroundDrawable(getResources().getDrawable(R.drawable.back));
    			} else {
    				price.setBackgroundDrawable(getResources().getDrawable(R.drawable.lay));
    			}

    			//price.setOnClickListener(this);

    			row.addView(price);
    			
    			tl.addView(row);
    			
    			registerForContextMenu(row);
    		}
    		
    		m_state = 0;

    		dismissDialog(WAITING_DIALOG);
	        
    	} else if (m_state == CANCEL_BET_STATE) {
    		showDialog(CANCEL_BET_DIALOG);
    		
    		m_state++;
    		
    		new Thread(this).start();

    	} else if (m_state == CANCEL_BET_STATE+1) {

    		BettingPlatform platform=BettingPlatformFactory.getBettingPlatform();
        
	        try {
	        	if (m_selectedRow != null) {
	        		Bet bet=(Bet)m_selectedRow.getTag();
	        		
	        		if (bet != null) {
	    		        platform.cancelBet(bet.getBetId());
	        		} else {
	        			throw new BettingException("No bet found for selected row");
	        		}
        		} else {
        			throw new BettingException("No bet has been selected");
	        	}
		        
		        m_state++;
	        } catch(Exception e) {
	        	m_error = e.getLocalizedMessage();
	        	
	        	m_state = ERROR_STATE;
	        }
	        
	        runOnUiThread(this);

    	} else if (m_state == CANCEL_BET_STATE+2) {
    		
    		dismissDialog(CANCEL_BET_DIALOG);
    		
    		TableLayout tl=(TableLayout)findViewById(R.id.betview); 
    		tl.removeView(m_selectedRow);
    		
    		m_selectedRow = null;
    		
    		m_state = 0;
    		

    	} else if (m_state == ERROR_STATE) {

    		dismissDialog(WAITING_DIALOG);
    		dismissDialog(CANCEL_BET_DIALOG);
	        
	        showDialog(ERROR_DIALOG);
	        
	        m_state++;
	        
	        new Thread(this).start();
	        
    	} else if (m_state == ERROR_STATE+1) {

    		try {
    			synchronized(this) {
    				wait(ERROR_MESSAGE_DISPLAY_DELAY);
    			}
    		} catch(Exception e) {
    			e.printStackTrace();
    		}
    		
    		m_state++;
    		
    		runOnUiThread(this);
    		
    	} else if (m_state == ERROR_STATE+2) {
    		
    		dismissDialog(ERROR_DIALOG);
    		
    		m_error = null;

    		if (m_selectedRow == null) {
        		finish();
    		} else {
    			m_selectedRow = null;
    		}
    	}
    }    
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Bet menu");
        
        menu.add(0, VIEW_MARKET_ID, 1, R.string.view_market_action);
        
        MenuItem mi=menu.add(0, CANCEL_UNMATCHED_BET_ID, 2,
        					R.string.cancel_unmatched_bet_action);
        
        m_selectedRow = null;
        
        if (v instanceof TableRow) {
        	m_selectedRow = (TableRow)v;
        	Bet bet=(Bet)m_selectedRow.getTag();
        	
        	mi.setEnabled(!bet.isMatched());
        }
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
    	
    	if (m_selectedRow != null) {
    		
    		if (item.getItemId() == VIEW_MARKET_ID) {
            	Bet bet=(Bet)m_selectedRow.getTag();

            	Intent intent = new Intent();
            	intent.setClass(BetView.this, MarketView.class);
            	intent.putExtra(MarketView.MARKET_ID_ATTR,
            			bet.getMarketId());
            
            	intent.putExtra(MarketView.MARKET_NAME_ATTR,
            			bet.getMarketName());
                startActivity(intent);
    			
    		} else if (item.getItemId() == CANCEL_UNMATCHED_BET_ID) {
    			m_state = CANCEL_BET_STATE;
    		
    			runOnUiThread(this);
    		}
    	}
    	
    	return(false);
    }
	
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);		
	}
    
    private TableRow m_selectedRow=null;
    private int m_state=0;
	private java.util.List<Bet> m_bets=null;
	private String m_error=null;
	private String m_currency="";
}
